import { Component, OnInit, Input, ElementRef, forwardRef, AfterViewInit } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
@Component({
    template: `
        <editor apiKey="59k34oh37wcrissv4pd7ogpupzc663htu902n6nho2v0or1m" [init]="editorConfig" (onFocus)="focus()" (onBlur)="blur()" [(ngModel)]="editorValue" (ngModelChange)="changeValue($event)"></editor>
    `,
    selector: "tinymce-editor",
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => TinymceEditorComponent),
            multi: true
        }
    ]
})
export class TinymceEditorComponent implements OnInit, ControlValueAccessor,AfterViewInit {
    @Input()
    private uploadName = "image";
    @Input()
    private uploadSize = 1;
    @Input()
    private uploadlUrl = "/api/updateImage.do";
    @Input()
    private value: string;
    @Input()
    editorConfig: any;
    @Input()
    placeholder: string = '请输入...';
    editor:any;
    editorValue;
    constructor(private el: ElementRef) {}
    propagateChange = (_: any) => {};
    writeValue(value: string) {
        if (value) {
                this.value = value;
                this.editorValue = this.value;
        }
    }

    registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {}
    ngAfterViewInit(){
        
        
    }
    changeValue(e){
        if(e !== this.placeholder){
            this.value = e;
            this.propagateChange(e);
        }else{
            this.value = '';
        }
    }
    ngOnInit() {
        this.editorValue = this.placeholder;
        this.editorConfig = {
            height: 400,
            resize: false,
            base_url: "/tinymce",
            menubar: false,
            language: "zh_CN",
            suffix: ".min",
            branding:false,
            statusbar: false,
            plugins: ["advlist autolink lists link image anchor", "searchreplace wordcount codesample fullscreen", "table paste"],
            toolbar:
                " h2 bold | \
                            alignleft aligncenter alignright alignjustify | \
                            bullist numlist | removeformat | codesample image fullscreen",
            // images_upload_url:this.uploadlUrl,
            images_upload_handler: (blobInfo, success, failure) => {
                var xhr, formData;
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open("POST", this.uploadlUrl);
                let token = localStorage.getItem('token');
                if(token){
                    xhr.setRequestHeader('Authorization', 'Bearer ' + token);
                }
                xhr.onload = function() {
                    var json;
                    if (xhr.status != 200) {
                        failure("HTTP Error: " + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.data.url != "string") {
                        failure("Invalid JSON: " + xhr.responseText);
                        return;
                    }
                    success(json.data.url);
                };
                formData = new FormData();
                formData.append("image", blobInfo.blob(), blobInfo.filename());
                xhr.send(formData);
            },
            setup: (editor) => {
                this.editor = editor;
            }
        };
    }
    focus(){
        if(this.editorValue == this.placeholder){
            this.editorValue = "";
        }
    }
    blur(){
        if(this.editorValue === ""){
            this.editorValue = this.placeholder;
        }
    }
}
